#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>

static void print_ids(const char * info) {
    pthread_t tid = pthread_self();
    printf("%s tid 0x%04x\n", info, (unsigned int)tid & 0xffff);
}

static void * thread_function(void * arg) {
    pthread_t tid = pthread_self();

    // the second way to do detach
    // assert(pthread_detach(tid) == 0);

    for(int i = 4; i > 0; --i){
        printf("thread[0x%04x] count: %d\n", (unsigned int)tid & 0xffff, i);
        sleep(1);
    }

    printf("sub thread exit\n");
    return NULL;
}

int main() {
    pthread_t ntid;
    int ret = pthread_create(&ntid, NULL, thread_function, NULL);
    if (0 != ret) {
        printf("can't create thread: %s\n", strerror(ret));
        exit(-1);
    }

    /*  
     * int pthread_detach(pthread_t thread);
     * 参数
     * thread   线程标识符
     * 返回值
     * 成功返回0, 否则返回错误码
     * */
    assert(pthread_detach(ntid) == 0);


    print_ids("main thread:");

    printf("main thread sleep a while \n");
    //The detached attribute merely determines the behavior of the system when the thread terminates; 
    //it does not prevent the thread from being terminated if  the  process  terminates  using  exit(3)  
    //(or equivalently, if the main thread returns).
    sleep(6);
    printf("main thread exit\n");

    return 0;
}

